package cc.marcio.systems.seven.dao;

import java.util.List;

import org.hibernate.Session;

import cc.marcio.systems.seven.model.Contact;
import cc.marcio.systems.seven.model.ContactId;
import cc.marcio.systems.seven.model.User;


@SuppressWarnings("serial")
public class UserDao extends BaseDaoImpl<User> implements BaseDao<User> {

	protected UserDao(Session session) {
		super(session);
	}

	@Override
	public void save(User entity) {
		for( Contact c : entity.getContacts() )	{
			if(c.getId().getUser() == null) {
				c.getId().setUser(entity);
			}
			DaoFactory.getContactDao().save(c);
		}
		super.save(entity);
	}
	
	@Override
	public void update(User user) {
		for( Contact c : user.getContacts() )	{
			if( c.getId().getUser() == null ) {
				c.getId().setUser(user);
			}
			Contact contact = new Contact();
			ContactId id = new ContactId();
			id.setContactdom(c.getId().getContactdom());
			id.setUser(user);
			contact.setId(id);
			
			List<Contact> list = DaoFactory.getContactDao().findByExample(contact); 
			
			if( list.isEmpty() ) {
				DaoFactory.getContactDao().save(c);
			} else {
				DaoFactory.getContactDao().update(c);
			}
		}
		super.update(user);
	}
	
	@SuppressWarnings("unchecked")
	public List<User> findUsersWithPlanetsActive() {
		StringBuilder sql = new StringBuilder();
        sql.append("select u from User u, Round r, Planet p ");
        sql.append("where r.current = true ");
        sql.append("and p.id.round = r.id ");
        sql.append("and p.id.user = u.id");
        return this.session.createQuery(sql.toString()).list();
	}
}
